# 自定义上下文管理器
class OpenOperation(object):

    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.fileobj = open(self.filename, self.mode)
        return self.fileobj

    def __exit__(self, exc_type, exc_value, traceback):  # 参数分别为异常类型、异常信息和堆栈
        self.fileobj.close()
        if exc_type:
            print('文件error')
        else:
            pass
